<?php

/* 
Uporabnik lahko v okviru svojih pristojnosti kreira novo kartico.

Kartica lahko predstavlja novo funkcionalnost, ki jo je treba razviti (navadna kartica),
ali nujno zahtevo (silver bullet). Vsaka vrsta kartic ima svojo barvo.
Število nujnih zahtev je omejeno.

# Preveri, ali se generira številka kartice in se zajamejo vsi obvezni podatki.
# Preveri kreiranje kartice, ki opisuje novo funkcionalnost
  (kartico lahko kreira samo Product Owner, kartica se samodejno postavi v prvi stolpec, 
   zajeti morajo biti vsi potrebni podatki razen ocene zahtevnosti).
# Preveri kreiranje kartice, ki predstavlja nujno zahtevo 
  (kartico lahko kreira samo KanbanMaster, kartica se samodejno postavi v stolpec s karticami
  z najvišjo prioriteto (tik pred mejnim); če pri tem pride do kršitve omejitve WIP, 
  se ta kršitev zabeleži; v danem trenutku je lahko v stolpcu s karticami z najvišjo prioriteto 
  samo ena nujna zahteva).
 */

extract(extractPost(), EXTR_PREFIX_ALL, 'c');

//      ime naslova         opis kartice                prioriteta        id uporabnika         tip kartice
if(isset($c_title) && isset($c_description) && isset($c_priority) && isset($c_assignee) && isset($c_type) && isset($c_project_id) && isset($c_board_id) && isset($c_user_id)){
    
    $edit = false;
    
    if($numberOfColums = R::count('column', 'board_id = ?', array($c_board_id)) < 3 || $priorityColumn = R::count('column', 'priority = 2 AND board_id = ?', array($c_board_id)) <1){
          jsonErrorDie("Check if board consists of atleast 3 columns where one of them has high priority (2).");  
    } 
    // Checking for left and right most column
    // $b_boundary: -1 = leftmost, 1 = rightmost, else normal
    else if(R::count('column', 'board_id = ? AND (boundary = 1 OR boundary = -1)', array($c_board_id)) != 2){
        jsonErrorDie("Your board does not contain both left and rightmost column.");
        
    }
    else {
    
        // Če id kartice še ne obstaja, ustvarimo novo
        if(!isset($c_id)){
            $edit = true;
            // Create new card
            $c = R::dispense( 'card' );
            
            if($c_type == 0) {
       
            $project = R::load('board', $c_board_id);
            $project->with('ORDER BY position ASC')
                    ->ownColumnList;
//            echo $project;

            $first = reset($project->ownColumnList);

            $c->column_id = $first->id;
            
            $col = R::load('column', $first->id);
            $wip = $col->wip;


            $checkWip = R::count('card', 'board_id = :board_id AND column_id = :column_id', [":board_id" => $c_board_id, ":column_id" => $first->id]);

            if($checkWip + 1 > $wip){
                jsonErrorDie("Cannot add card - WIP violation.");
            }
            
            
            
            
        } else if ($c_type == 1) {
            // Preveri ali že obstaja nujna zahteva        
            $silver_bullet_exists = R::findOne('card', 'type = :type AND board_id = :board_id', [":type" => 1, ":board_id" => $c_board_id]);

            if(isset($silver_bullet_exists)){
                
//                logCardMove('Card creation violation by WIP');
                jsonErrorDie("Silver bullet already exists.");
 
            }
            
            $high_prio_column =  R::getCell( "SELECT  * FROM `column` WHERE priority = 2 AND board_id = ?", array($c_board_id));
            $c->column_id = $high_prio_column;
            
        } else {
            jsonErrorDie("You have entered wrong card type.");
        }
        
        $c->type = $c_type;     // 0 - navadna kartica, ustvari Product owner, samodejno v prvi stoplec
                                 // 1 - nujna zahteva, ustvari KanBan master, v stolpec z najvišjo prioriteto
        $c->due_date = getCurrentDate();
        $c->date_created = R::isoDateTime();
        $c->date_finished = NULL;
        $c->active = 1;
            
            
            

         } else {
            $c = R::load('card', $c_id);
             /* Load existing card */
             /* Posodabljanje kartic */
            $project = R::load('project', $c_project_id);

            $devGroup = R::load('group', $project->dev_group);


            $kanbanMaster = false;
            $productOwner = false;
            $user = false;
            
            $developers = json_decode($devGroup->developers, true);
            foreach($developers as $developer){
                if($developer == $c_user_id){
//                    echo "user true";
                    $user = true;
                }
            }
           
             if($devGroup->kanban_master == $c_user_id){
//                echo "kanbanmaster true";
                $kanbanMaster = true;
            } 
            if($devGroup->product_owner == $c_user_id){
//                echo "product owner true";
                
                $productOwner = true;
            }
            
            $leviStolpecRazvoja_id =  R::getCell( "SELECT * FROM `column` WHERE boundary = -1 AND board_id = ?", array($c_board_id));
            $desniStolpecRazvoja_id = R::getCell( "SELECT * FROM `column` WHERE boundary = 1 AND board_id = ?", array($c_board_id));
//            echo "levi" . $leviStolpecRazvoja_id ."\n"; 
//            echo "desni" . $desniStolpecRazvoja_id."\n";
            
            $desniStolpecRazvoja = R::load('column', $desniStolpecRazvoja_id);
            $leviStolpecRazvoja = R::load('column', $leviStolpecRazvoja_id);
            
            // Naloadamo stolpec od podane kartice;
            $column = R::load('column', $c->column_id);
//            echo "TROLOLOL" . $column->name;
            
            /* # Preveri posodabljanje po izstopu iz končnega mejnega stolpca (ni dovoljeno). */
            if($column->position > $desniStolpecRazvoja->position+99){
                jsonErrorDie("You can not edit cards that are past right most column of development");
            } else if ($column->position <= $desniStolpecRazvoja->position+99 && $column->position>= $leviStolpecRazvoja->position){
//                echo "test";
                if($kanbanMaster || $user){
//                    echo "znotraj mejhnih kanban ali user";
                    $edit = true;
                }
            } else if($column->position < $desniStolpecRazvoja->position+99) {
                if($productOwner || $kanbanMaster){
//                    echo "pred mejhnim product ali kanban";
                    $edit = true;
                }
            }
           
            if($c->id == 0){
                jsonErrorDie("This card does not exist.");
            }
        }  
        
        if($edit) {
        
            $c->title = $c_title;
            $c->description = $c_description;
            $c->priority = $c_priority; // 0 - low, 1 - average, 2 - high
            $c->asignee = $c_assignee;
            $c->project_id = $c_project_id;
            $c->board_id = $c_board_id;
            
            if(isset($c_due_date)){
                $c->due_date = $c_due_date;
            }
                
            

            if(isset($c_size)){
                $c->size = $c_size; 
            }
            $c_id = R::store($c);

	        logCardMove($c, $c->column, $c->column);
        
            jsonSuccessDie("card_id", $c_id);
        } else {
            jsonErrorDie("You don't have permission to change this card.");
        }   
        
        
    }
} else {
    jsonErrorDie("Problem occured while adding card into database.");
}

//    Save priority as type
//    $priority = R::load ('priority', $c_priority);
//    $c->priority = $priority->type;